package com.lib.krismile.config;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.os.Bundle;


import androidx.multidex.MultiDexApplication;

import com.blankj.utilcode.util.Utils;
import com.bumptech.glide.Glide;
import com.guoxiaoxing.phoenix.picker.Phoenix;
import com.jeremyliao.liveeventbus.LiveEventBus;
import com.lib.krismile.R;
import com.lib.krismile.http.data.HttpBaseResponse;
import com.lib.krismile.http.httptool.HttpException;
import com.lib.krismile.http.request.HttpFactory;
import com.lib.krismile.http.request.ServerAddress;
import com.lib.krismile.manager.MyActivityManager;
import com.orhanobut.hawk.Hawk;
import com.scwang.smart.refresh.footer.ClassicsFooter;
import com.scwang.smart.refresh.header.ClassicsHeader;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;


/**
 * @author : wangJiawei
 * @date : 2020/2/19 11:30
 * @desc :application
 */

public class BaseDexApplication extends MultiDexApplication {
    private static BaseDexApplication context;
    public static boolean firstOpen;

    @Override
    public void onCreate() {
        super.onCreate();
        firstOpen = true;
        context = this;
        initActivityManager();
        init();
    }

    public static Context getContext() {
        return context;
    }

    /**
     * 管理Activity
     */
    private void initActivityManager() {
        registerActivityLifecycleCallbacks(new Application.ActivityLifecycleCallbacks() {
            @Override
            public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
            }

            @Override
            public void onActivityStarted(Activity activity) {
            }

            @Override
            public void onActivityResumed(Activity activity) {
                MyActivityManager.getInstance().setCurrentActivity(activity);
            }

            @Override
            public void onActivityPaused(Activity activity) {
            }

            @Override
            public void onActivityStopped(Activity activity) {
            }

            @Override
            public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
            }

            @Override
            public void onActivityDestroyed(Activity activity) {
            }
        });
    }

    /**
     * 一些第三方库和本地代码的初始化设置
     */
    private void init() {
        Hawk.init(context).build();

        setHttpConfig();

        Phoenix.config().imageLoader((mContext, imageView, imagePath, type) ->
                Glide.with(mContext).load(imagePath).into(imageView));

        //初始化 大佬的工具类utils
        Utils.init(this);

        //初始化 LiveEventBus
        LiveEventBus.config()
                .autoClear(true)//配置在没有 Observer 关联的时候是否自动清除 LiveEvent 以释放内存（默认值 false）
                .enableLogger(true)//打印日志
                .setContext(this)//如果广播模式有问题，请手动传入 Context，需要在 application onCreate 中配置
                .lifecycleObserverAlwaysActive(true);//配置 LifecycleObserver（如 Activity）接收消息的模式（默认值 true）：true：整个生命周期（从 onCreate 到 onDestroy）都可以实时收到消息
    }

    /**
     * 请求配置
     */
    public static void setHttpConfig() {

        HttpFactory.HTTP_HOST_URL = ServerAddress.getApiDefaultHost();
        HttpFactory.httpResponseInterface = (gson, response) -> {

            if (firstOpen) {
                firstOpen = false;
                return response;
            }

            HttpBaseResponse httpResponse = gson.fromJson(response, HttpBaseResponse.class);
            if (httpResponse.errorCode != 0) {
                throw new HttpException(httpResponse.errorCode,httpResponse.errorMsg);
            }
            return gson.toJson(httpResponse.data);
        };
    }

    /*
     * 设置上拉加载和下拉刷新的样式
     */
    static {
        //设置全局的Header构建器
        SmartRefreshLayout.setDefaultRefreshHeaderCreator((context, layout) -> {
            //全局设置主题颜色
            layout.setPrimaryColorsId(R.color.colorPrimary, android.R.color.white);
            return new ClassicsHeader(context);
        });
        //设置全局的Footer构建器
        SmartRefreshLayout.setDefaultRefreshFooterCreator((context, layout) -> {
            //指定为经典Footer，默认是 BallPulseFooter
            return new ClassicsFooter(context).setDrawableSize(20);
        });

        SmartRefreshLayout.setDefaultRefreshInitializer((context, layout) -> {
//            layout.setEnableFooterFollowWhenLoadFinished(true);
            layout.setEnableAutoLoadMore(false);
        });
    }
}
